package com.zhitongyun.devlop.db.dao;

import java.util.List;

import io.realm.Realm;
import io.realm.RealmObject;

/**
 * 数据库基础操作
 * <p/>
 * Created by huanglei
 */
public abstract class DBBaseDao<E extends RealmObject> implements DBDao {

    protected Realm realm;

    public DBBaseDao() {
    }

    @Override
    public void closeRealm() {
        if (realm != null) {
            realm.close();
            realm = null;
        }
    }

    @Override
    public void resetRealm() {
        closeRealm();
        initRealm();
    }

    /**
     * 插入或更新多条数据
     *
     * @param entitys
     */
    public void insertOrUpdate(final List<E> entitys) {
        resetRealm();
        if (realm != null) {
            realm.executeTransaction(new Realm.Transaction() {
                @Override
                public void execute(Realm realm) {
                    realm.copyToRealmOrUpdate(entitys);
                }
            });
        }
        closeRealm();
    }

    /**
     * 插入或更新一条数据
     *
     * @param entity
     */
    public void insertOrUpdate(final E entity) {
        resetRealm();
        if (realm != null) {
            realm.executeTransaction(new Realm.Transaction() {
                @Override
                public void execute(Realm realm) {
                    realm.copyToRealmOrUpdate(entity);
                }
            });

        }
        closeRealm();
    }

    public void delete(final Class<E> eClass) {
        resetRealm();
        if (realm != null) {

            realm.executeTransaction(new Realm.Transaction() {
                @Override
                public void execute(Realm realm) {
                    realm.where(eClass).findAll().deleteAllFromRealm();
                }
            });
        }
        closeRealm();
    }

}
